#!/bin/bash

binfile=dingtalk-sender

cwd=$(cd $(dirname $0)/; pwd)
cd $cwd

usage()
{
	echo $"Usage: $0 {start|stop|restart|status|build|pack}"
	exit 0
}

build()
{
   CGO_ENABLED=0 GOOS="linux" go build
}

start()
{
	if [ ! -f $binfile ]; then
		echo "file[$binfile] not found"
		exit 1
	fi

	if [ $(ps aux|grep -v grep|grep -v control|grep "$binfile" -c) -gt 0 ]; then
		echo "${binfile} already started"
		return
	fi

	mkdir -p logs/$binfile
	nohup $cwd/$binfile &> logs/${binfile}/stdout.log &

	for((i=1;i<=15;i++)); do
		if [ $(ps aux|grep -v grep|grep -v control|grep "$binfile" -c) -gt 0 ]; then
			echo "${binfile} started"
			return
		fi
		sleep 0.2
	done

	echo "cannot start ${binfile}"
	exit 1
}

stop()
{
	if [ $(ps aux|grep -v grep|grep -v control|grep "$binfile" -c) -eq 0 ]; then
		echo "${binfile} already stopped"
		return
	fi

	ps aux|grep -v grep|grep -v control|grep "$binfile"|awk '{print $2}'|xargs kill
	for((i=1;i<=15;i++)); do
		if [ $(ps aux|grep -v grep|grep -v control|grep "$binfile" -c) -eq 0 ]; then
			echo "${binfile} stopped"
			return
		fi
		sleep 0.2
	done

	echo "cannot stop ${binfile}"
	exit 1
}

restart()
{
	stop
	start
	status
}

status()
{
	ps aux|grep -v grep|grep ${binfile}
}

build()
{
	GOOS="linux" GOHOSTARCH="amd64" CGO_ENABLED=0 go build
}

reload()
{
	build
	restart
}

pack()
{
	v=$(date +%Y-%m-%d-%H-%M-%S)
	tar zcvf $binfile-$v.tar.gz control $binfile etc/dingtalk.tpl etc/dingtalk-sender.yml etc/dingtalk-sender.service
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		restart
		;;
	status)
		status
		;;
	build)
		build
		;;
	reload)
		reload
		;;
	pack)
		pack
		;;
	*)
		usage
esac
